import connection from "../mysql/connection.js";

export const getUsers = () => {
  return new Promise((resolve, reject) => {
    connection.query("SELECT * FROM user", (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};

export const getUser = (id) => {
  return new Promise((resolve, reject) => {
    connection.query("SELECT * from user WHERE id = ?", id, (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};

export const saveUser = (user) => {
  return new Promise((resolve, reject) => {
    connection.query("INSERT INTO user SET?", user, (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};

export const updateUser = (user) => {
  return new Promise((resolve, reject) => {
    const userId = user.id;
    delete user.id;
    connection.query("UPDATE user SET? WHERE id=? ", [user, userId], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};

export const saveOrUpdate = async (user) => {
  const res = await getUser(user.id);
  if (res.length === 0) {
    user.create_time = new Date();
    await saveUser(user);
  } else {
    user.last_login_time = new Date();
    await updateUser(user);
  }
};
